﻿using Microsoft.AspNetCore.Mvc;
using NewLife.Web;

namespace newlife.core.api.Controllers
{
    /// <summary>
    /// JWT 操作
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class JwtController : ControllerBase
    {
        private readonly string _secret = "advuWkpyIsImV4cCI6MTc0ODQxNTE5MiwiaW";

        [HttpPost]
        public IActionResult Token(string name)
        {
            var builder = new JwtBuilder
            {
                IssuedAt = DateTime.Now,
                Expire = DateTime.Now.AddSeconds(10),
                Secret = _secret
            };

            return Ok(builder.Encode(new { Id = 1, Name = name }));
        }

        [HttpPost]
        public IActionResult Verify(string token)
        {
            var builder = new JwtBuilder
            {
                Secret = _secret
            };

            bool valid = builder.TryDecode(token, out var msg);
            return Ok(new { Valid = valid, Message = msg });
        }

        [HttpPost]
        public IActionResult Parse(string token)
        {
            var builder = new JwtBuilder
            {
                Secret = _secret
            };

            builder.Parse(token);
            return Ok(builder.Items);
        }
    }
}
